package com.choosefine.springboot.devops.rules.controller;


import com.choosefine.springboot.devops.base.config.MapUtil;
import com.choosefine.springboot.devops.base.result.ReturnMSG;
import com.choosefine.springboot.devops.rules.dto.InsertRulesDTO;
import com.choosefine.springboot.devops.rules.dto.UpdateRulesDTO;
import com.choosefine.springboot.devops.rules.model.Rules;
import com.choosefine.springboot.devops.rules.service.RulesService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/rules")
public class RulesController {
	@Autowired
	private RulesService rulesService;
	@Autowired
	private ObjectMapper objectMapper;

	@GetMapping("/{id}")
	public String selectById(@PathVariable("id") Integer id) throws JsonProcessingException {
		Rules result= rulesService.selectById(id);
		return objectMapper.writeValueAsString(result);
	}

	@PostMapping
	public String insert(@Valid InsertRulesDTO insertRulesDTO, BindingResult result) throws JsonProcessingException {
		ReturnMSG returnMSG=new ReturnMSG();
		if(result.hasErrors()){
			return objectMapper.writeValueAsString(returnMSG.paramError());
		}else{
			rulesService.save(Rules.class, MapUtil.transBean2Map(insertRulesDTO));
			return objectMapper.writeValueAsString(returnMSG.success());
		}
	}

	@PutMapping
	public String update(@Valid UpdateRulesDTO updateRulesDTO, BindingResult result) throws JsonProcessingException {
		ReturnMSG returnMSG=new ReturnMSG();
		if(result.hasErrors()){
			return objectMapper.writeValueAsString(returnMSG.paramError());
		}else{
			if(rulesService.update(Rules.class, MapUtil.transBean2Map(updateRulesDTO))>0){
				return objectMapper.writeValueAsString(returnMSG.success());
			}else{
				return objectMapper.writeValueAsString(returnMSG.error());
			}
		}
	}

	@DeleteMapping
	public String delete(Integer id) throws JsonProcessingException {
		ReturnMSG returnMSG=new ReturnMSG();
		if(id==null){
			return objectMapper.writeValueAsString(returnMSG.paramError());
		}else{
			Map param=new HashMap();
			param.put("id",id);
			if(rulesService.falseDelete(Rules.class,param)>0){
				return objectMapper.writeValueAsString(returnMSG.success());
			}else{
				return objectMapper.writeValueAsString(returnMSG.error());
			}
		}

	}

}
